<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { Popover } from 'vant'

const router = useRouter()
const showUserMenu = ref(false)
const actions = computed(() => {
  return [
    { text: user.value?.username ?? ''},
    { text: '修改密码'},
    { text: '退出登录'}
  ]
})

// 获取用户信息
const user = computed(() => {
  const userJson = localStorage.getItem('user')
  return userJson ? JSON.parse(userJson) : null
})

// 退出登录
function logout() {
  localStorage.removeItem('token')
  localStorage.removeItem('user')
  router.push('/login')
}

const handleSelect = (action) => {
  if (action.text === '退出登录') {
    logout()
  } else if (action.text === '修改密码') {
    goToResetPassword()
  }
}

function goToResetPassword() {
  router.push('/reset-password')
}
</script>

<template>
  <div class="app-container" :style="{ paddingTop: $route.meta.requiresAuth ? '50px' : '0px' }">
    <!-- 顶部导航栏，仅在登录后显示 -->
    <div class="app-header" v-if="$route.meta.requiresAuth">
      <div class="app-title">记账应用</div>
      
      <!-- 用户菜单 -->
      <van-popover
        v-model:show="showUserMenu"
        placement="bottom-end"
        :offset="[0, 8]"
        @select="handleSelect"
        :actions="actions"
      >
        <!-- <div class="menu-item">{{ user?.username }}</div>
        <div class="menu-item" @click="logout">退出登录</div> -->
        <template #reference>
          <div class="user-menu">
            <div class="user-avatar">{{ user?.username?.charAt(0)?.toUpperCase() || '?' }}</div>
          </div>
        </template>
      </van-popover>
    </div>
    
    <router-view />
  </div>
</template>

<style scoped>
.app-container {
  position: relative;
  min-height: 100vh;
}

.app-header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 50px;
  background: #fff;
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.05);
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 16px;
  z-index: 100;
}

.app-title {
  font-size: 18px;
  font-weight: 600;
  color: #27c19e;
}

.user-menu {
  cursor: pointer;
}

.user-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: #27c19e;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  font-weight: 600;
}

.menu-item {
  padding: 8px 12px;
  font-size: 14px;
  cursor: pointer;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.menu-item:last-child {
  border-bottom: none;
}

/* 为有顶部导航栏的页面添加顶部内边距 */
:deep(.home-container),
:deep(.account-detail-container),
:deep(.record-edit-container) {
  padding-top: 60px;
}

header {
  line-height: 1.5;
}

.logo {
  display: block;
  margin: 0 auto 2rem;
}

@media (min-width: 1024px) {
  header {
    display: flex;
    place-items: center;
    padding-right: calc(var(--section-gap) / 2);
  }

  .logo {
    margin: 0 2rem 0 0;
  }

  header .wrapper {
    display: flex;
    place-items: flex-start;
    flex-wrap: wrap;
  }
}
</style>
